package xyz.zq.controller;

import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.netflix.loadbalancer.Server;
import lombok.AllArgsConstructor;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@AllArgsConstructor
public class DemoController {

    private final RestTemplate restTemplate;
    private final LoadBalancerClient loadBalancerClient;

    /**
     * 服务名称
     */
    private static final String SERVICE_NAME = "nacos-discovery-provider";

    /**
     * 传统调用模式
     */
   /* @GetMapping("/test")
    public String test(String name) {
        ServiceInstance choose = loadBalancerClient.choose(SERVICE_NAME);
        URI uri = choose.getUri();
        return restTemplate.getForObject(uri + "/demo?name=" + name, String.class);
    }*/

    /**
     * Netflix ribbon 负载均衡调用方式
     *
     * @param name
     * @return
     */
    /*@GetMapping("/test")
    public String test(String name) {
        return restTemplate.getForObject("http://SERVICE_NAME/demo?name="
                .replace("SERVICE_NAME", SERVICE_NAME) + name, String.class);
    }*/

    /**
     * 获取元数据
     *
     * @param name
     * @return
     */
    @GetMapping("/test")
    public String test(String name) {
        RibbonLoadBalancerClient.RibbonServer ribbonServer =
                (RibbonLoadBalancerClient.RibbonServer) loadBalancerClient.choose(SERVICE_NAME);
        NacosServer server = (NacosServer) ribbonServer.getServer();
        //获取元数据
        System.out.println("------>" + server.getMetadata());
        return restTemplate.getForObject("http://SERVICE_NAME/demo?name="
                .replace("SERVICE_NAME", SERVICE_NAME) + name, String.class);
    }


}
